
//  FilesDownManage.m
//  Created by yu on 13-1-21.
//

#import "FilesDownManage.h"
#import "Reachability.h"
#import "SSZipArchive.h"

#define MAXLINES  2
#define TEMPPATH [CommonHelper getTempFolderPathWithBasepath:_basepath]
#define OPENFINISHLISTVIEW
@implementation FilesDownManage
@synthesize downinglist=_downinglist;
@synthesize fileInfo = _fileInfo;
@synthesize downloadDelegate=_downloadDelegate;
@synthesize isFistLoadSound=_isFirstLoadSound;
@synthesize basepath = _basepath;
@synthesize filelist = _filelist;
@synthesize targetPathArray = _targetPathArray;
@synthesize VCdelegate = _VCdelegate;
@synthesize count;
@synthesize  fileImage = _fileImage;
static   FilesDownManage *sharedFilesDownManage = nil;
-(NSArray *)sortbyTime:(NSArray *)array{
    NSArray *sorteArray1 = [array sortedArrayUsingComparator:^(id obj1, id obj2){
        FileModel *file1 = (FileModel *)obj1;
        FileModel *file2 = (FileModel *)obj2;
        NSDate *date1 = [CommonHelper makeDate:file1.time];
        NSDate *date2 = [CommonHelper makeDate:file2.time];
        if ([[date1 earlierDate:date2]isEqualToDate:date2]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([[date1 earlierDate:date2]isEqualToDate:date1]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    return sorteArray1;
}
-(NSArray *)sortRequestArrbyTime:(NSArray *)array{
    NSArray *sorteArray1 = [array sortedArrayUsingComparator:^(id obj1, id obj2){
        FileModel* file1 =   [((ASIHTTPRequest *)obj1).userInfo objectForKey:@"File"];
        FileModel *file2 =   [((ASIHTTPRequest *)obj2).userInfo objectForKey:@"File"];
        NSDate *date1 = [CommonHelper makeDate:file1.time];
        NSDate *date2 = [CommonHelper makeDate:file2.time];
        if ([[date1 earlierDate:date2]isEqualToDate:date2]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([[date1 earlierDate:date2]isEqualToDate:date1]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    return sorteArray1;
}
-(void)saveDownloadFile:(FileModel*)fileinfo{
    NSData *imagedata =UIImagePNGRepresentation(fileinfo.fileimage);
     NSMutableDictionary *filedic = [NSMutableDictionary dictionaryWithObjectsAndKeys:fileinfo.fileID,@"fileID",fileinfo.fileName,@"filename",fileinfo.fileURL,@"fileurl",fileinfo.time,@"time",_basepath,@"basepath",_TargetSubPath,@"tarpath" ,fileinfo.fileSize,@"filesize",fileinfo.fileReceivedSize,@"filerecievesize",imagedata,@"fileimage",nil];
    [filedic setValue:fileinfo.fileType forKey:@"filetype"];
    [filedic setValue:fileinfo.quanjing forKey:@"quanjing"];
}
-(void)beginRequest:(FileModel *)fileInfo isBeginDown:(BOOL)isBeginDown
{
    for(ASIHTTPRequest *tempRequest in self.downinglist)
    {
        if([[[tempRequest.url absoluteString]lastPathComponent] isEqualToString:[fileInfo.fileURL lastPathComponent]])
        {
            if ([tempRequest isExecuting]&&isBeginDown) {
                return;
            }else if ([tempRequest isExecuting]&&!isBeginDown)
            {
              [tempRequest setUserInfo:[NSDictionary dictionaryWithObject:fileInfo forKey:@"File"]];
              [tempRequest cancel];
                [self.downloadDelegate updateCellProgress:tempRequest];
                return;
            }
        }
    }
    [self saveDownloadFile:fileInfo];
    fileInfo.isFirstReceived=YES;
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSData *fileData=[fileManager contentsAtPath:fileInfo.tempPath];
    NSInteger receivedDataLength=[fileData length];
    fileInfo.fileReceivedSize=[NSString stringWithFormat:@"%ld",(long)receivedDataLength];
    ASIHTTPRequest *request=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:fileInfo.fileURL]];
    request.delegate=self;
    [request setDownloadDestinationPath:[fileInfo targetPath]];
    [request setTemporaryFileDownloadPath:fileInfo.tempPath];
    [request setDownloadProgressDelegate:self];
    [request setNumberOfTimesToRetryOnTimeout:2];
    [request setAllowResumeForFileDownloads:YES];
    [request setUserInfo:[NSDictionary dictionaryWithObject:fileInfo forKey:@"File"]];
    [request setTimeOutSeconds:30.0f];
    if (isBeginDown) {
        [request startAsynchronous];
    }
    BOOL exit = NO;
    for(ASIHTTPRequest *tempRequest in self.downinglist)
    {
        if([[[tempRequest.url absoluteString]lastPathComponent] isEqualToString:[fileInfo.fileURL lastPathComponent] ])
        {
            [self.downinglist replaceObjectAtIndex:[_downinglist indexOfObject:tempRequest] withObject:request ];
            exit = YES;
            break;
        }
    }
    if (!exit) {
        [self.downinglist addObject:request];
    }
    [self.downloadDelegate updateCellProgress:request];
}

-(void)resumeRequest:(ASIHTTPRequest *)request{
    NSInteger max = MAXLINES;
    FileModel *fileInfo =  [request.userInfo objectForKey:@"File"];
    NSInteger downingcount =0;
    NSInteger indexmax =-1;
    for (FileModel *file in _filelist) {
        if (file.isDownloading) {
            downingcount++;
            if (downingcount==max) {
                indexmax = [_filelist indexOfObject:file];
            }
        }
    }
    if (downingcount>=max) {
        FileModel *file  = [_filelist objectAtIndex:indexmax];
            if (file.isDownloading) {
                file.isDownloading = NO;
                file.willDownloading = YES;
            }
    }
    for (FileModel *file in _filelist) {
        if ([file.fileName isEqualToString:fileInfo.fileName]) {
            file.isDownloading = YES;
            file.willDownloading = NO;
            file.error = NO;
        }
    }
    [self startLoad];
}
-(void)stopRequest:(ASIHTTPRequest *)request{
    NSInteger max = MAXLINES;
    if([request isExecuting])
    {
        [request cancel];
    }
    FileModel *fileInfo =  [request.userInfo objectForKey:@"File"];
    for (FileModel *file in _filelist) {
            if ([file.fileName isEqualToString:fileInfo.fileName]) {
                file.isDownloading = NO;
                file.willDownloading = NO;
                break;
            }
        }
        NSInteger downingcount =0;
        for (FileModel *file in _filelist) {
            if (file.isDownloading) {
                downingcount++;
            }
        }
        if (downingcount<max) {
        for (FileModel *file in _filelist) {
            if (!file.isDownloading&&file.willDownloading){
                file.isDownloading = YES;
                file.willDownloading = NO;
                break;
            }
        }
    }
    [self startLoad];
}
-(void)deleteRequest:(ASIHTTPRequest *)request{
    bool isexecuting = NO;
    if([request isExecuting])
    {
        [request cancel];
        isexecuting = YES;
    }
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    FileModel *fileInfo=(FileModel*)[request.userInfo objectForKey:@"File"];
        NSString *path=fileInfo.tempPath;
        NSString *configPath=[NSString stringWithFormat:@"%@.plist",path];
        [fileManager removeItemAtPath:path error:&error];
        [fileManager removeItemAtPath:configPath error:&error];
        if(!error)
        {
            NSLog(@"%@",[error description]);
        }
        NSInteger delindex =-1;
        for (FileModel *file in _filelist) {
            if ([file.fileName isEqualToString:fileInfo.fileName]) {
                delindex = [_filelist indexOfObject:file];
                break;
            }
        }
        if (delindex!=NSNotFound) 
        [_filelist removeObjectAtIndex:delindex];
        [_downinglist removeObject:request];
    if (isexecuting) {
        [self startLoad];
    }
     self.count = (int)[_filelist count];
}
-(void)clearAllRquests{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    for (ASIHTTPRequest *request in _downinglist) {
        if([request isExecuting])
            [request cancel];
        FileModel *fileInfo=(FileModel*)[request.userInfo objectForKey:@"File"];
        NSString *path=fileInfo.tempPath;;
        NSString *configPath=[NSString stringWithFormat:@"%@.plist",path];
        [fileManager removeItemAtPath:path error:&error];
        [fileManager removeItemAtPath:configPath error:&error];
        if(!error)
        {
            NSLog(@"%@",[error description]);
        }
    }
    [_downinglist removeAllObjects];
    [_filelist removeAllObjects];
}

-(FileModel *)getTempfile:(NSString *)path{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    FileModel *file = [[FileModel alloc]init];
    file.fileName = [dic objectForKey:@"filename"];
    file.fileID = [dic objectForKey:@"fileID"];
    file.quanjing = [dic objectForKey:@"quanjing"];
    file.fileType = [dic objectForKey:@"filetype"];
    file.fileURL = [dic objectForKey:@"fileurl"];
        file.fileSize = [dic objectForKey:@"filesize"];
    file.fileReceivedSize= [dic objectForKey:@"filerecievesize"];
    self.basepath = [dic objectForKey:@"basepath"];
    self.TargetSubPath = [dic objectForKey:@"tarpath"];
    NSString*  path1= [CommonHelper getTargetPathWithBasepath:_basepath subpath:_TargetSubPath];
    path1 = [path1 stringByAppendingPathComponent:file.fileID];
    file.targetPath = path1;
    NSString *tempfilePath= [TEMPPATH stringByAppendingPathComponent: file.fileID];
        file.tempPath = tempfilePath;
        file.time = [dic objectForKey:@"time"];
        file.fileimage = [UIImage imageWithData:[dic objectForKey:@"fileimage"]];
    file.isDownloading=NO;
    file.isDownloading = NO;
    file.willDownloading = NO;
    file.error = NO;
    NSData *fileData=[[NSFileManager defaultManager ] contentsAtPath:file.tempPath];
    NSInteger receivedDataLength=[fileData length];
    file.fileReceivedSize=[NSString stringWithFormat:@"%ld",(long)receivedDataLength];
    return file;
}
-(void)loadTempfiles
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    NSArray *filelist=[fileManager contentsOfDirectoryAtPath:TEMPPATH error:&error];
    if(!error)
    {
        NSLog(@"%@",[error description]);
    }
    NSMutableArray *filearr = [[NSMutableArray alloc]init];
    for(NSString *file in filelist)
    {
        NSString *filetype = [file  pathExtension];
        if([filetype isEqualToString:@"plist"])
           [filearr addObject:[self getTempfile:[TEMPPATH stringByAppendingPathComponent:file]]];
    }
    NSArray* arr =  [self sortbyTime:(NSArray *)filearr];
    [_filelist addObjectsFromArray:arr];
    
    [self startLoad];
}
-(void)downFile:(QuanJing*)quanjing{
    NSString *path = @"SVQJ";
    self.TargetSubPath = path;
    if (_fileInfo!=nil) {
        _fileInfo = nil;}
    _fileInfo = [[FileModel alloc]init];
_fileInfo.fileID = quanjing.sid;
_fileInfo.quanjing = quanjing.dic;
_fileInfo.fileName = quanjing.title;
_fileInfo.fileURL = quanjing.archive;
  NSDate *myDate = [NSDate date];
_fileInfo.time = [CommonHelper dateToString:myDate];
_fileInfo.fileType=@"0";
path= [CommonHelper getTargetPathWithBasepath:_basepath subpath:path];
path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",quanjing.sid]];
_fileInfo.targetPath = path;
self.fileImage = nil;
_fileInfo.fileimage = nil;
_fileInfo.isDownloading=YES;
_fileInfo.willDownloading = YES;
_fileInfo.error = NO;
_fileInfo.isFirstReceived = YES;
NSString *tempfilePath= [TEMPPATH stringByAppendingPathComponent: quanjing.sid]  ;
_fileInfo.tempPath = tempfilePath;    NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
NSString* savePath = [NSString stringWithFormat: @"%@/SVQJ/%@", docPath, quanjing.sid];
if([CommonHelper isExistFile: savePath]){
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该文件已下载，是否重新下载？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    return;}
tempfilePath =[tempfilePath stringByAppendingString:@".plist"];
if([CommonHelper isExistFile:tempfilePath])
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该文件已经在下载列表中了，是否重新下载？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    return;
}
[self.filelist addObject:_fileInfo];
[self startLoad];
if(self.VCdelegate!=nil && [self.VCdelegate respondsToSelector:@selector(allowNextRequest)])
{
    [self.VCdelegate allowNextRequest];
}else{
       UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该文件成功添加到下载队列" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
       [alert show];
}
return;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *tempfilePath= [TEMPPATH stringByAppendingPathComponent: _fileInfo.fileID]  ;
tempfilePath =[tempfilePath stringByAppendingString:@".plist"];
if(buttonIndex==1)
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
        NSInteger delindex =-1;
        if([CommonHelper isExistFile:_fileInfo.targetPath]){
            if ([fileManager removeItemAtPath:_fileInfo.targetPath error:&error]!=YES) {
                NSLog(@"删除文件出错:%@",[error localizedDescription]);
            }
        }else if([CommonHelper isExistFile:tempfilePath]){
            for(ASIHTTPRequest *request in self.downinglist)
            {
                FileModel *fileModel=[request.userInfo objectForKey:@"File"];
                if([fileModel.fileName isEqualToString:_fileInfo.fileName])
                {
                    //[self.downinglist removeObject:request];
                    if ([request isExecuting]) {
                        [request cancel];
                    }
                    delindex = [_downinglist indexOfObject:request];
                    break;
                }
            }
            [_downinglist removeObjectAtIndex:delindex];
            for (FileModel *file in _filelist) {
                if ([file.fileName isEqualToString:_fileInfo.fileName]) {
                    delindex = [_filelist indexOfObject:file];
                    break;
                }
            }
            [_filelist removeObjectAtIndex:delindex];
            NSString * tempfilePath =[_fileInfo.tempPath stringByAppendingString:@".plist"];
            if([CommonHelper isExistFile:tempfilePath]){
                if ([fileManager removeItemAtPath:tempfilePath error:&error]!=YES) {
                    NSLog(@"删除临时文件出错:%@",[error localizedDescription]);}
            }
            if([CommonHelper isExistFile:_fileInfo.tempPath])
            {
                if ([fileManager removeItemAtPath:_fileInfo.tempPath error:&error]!=YES) {
                    NSLog(@"删除临时文件出错:%@",[error localizedDescription]);
                }
            }
        }
        self.fileInfo.fileReceivedSize=[CommonHelper getFileSizeString:@"0"];
        [_filelist addObject:_fileInfo];
        [self startLoad];
    }
    if(self.VCdelegate!=nil && [self.VCdelegate respondsToSelector:@selector(allowNextRequest)])
    {
        [self.VCdelegate allowNextRequest];
    }
}
-(void)startLoad{
    NSInteger num = 0;
    NSInteger max = MAXLINES;
    for (FileModel *file in _filelist) {
        if (!file.error) {
            if (file.isDownloading==YES) {
                file.willDownloading = NO;
                    if (num>=max) {
                        file.isDownloading = NO;
                        file.willDownloading = YES;
                    }else
                num++;}}}
    if (num<max) {        
        for (FileModel *file in _filelist) {
             if (!file.error) {
            if (!file.isDownloading&&file.willDownloading) {
                num++;
                if (num>max) {
                    break;
                    }
                    file.isDownloading = YES;
                    file.willDownloading = NO;
            }
        }
    }
            
    }
    for (FileModel *file in _filelist) {
         if (!file.error) {
        if (file.isDownloading==YES) {
            [self beginRequest:file isBeginDown:YES];
        }else
            [self beginRequest:file isBeginDown:NO];
         }
    }
    self.count = (int)[_filelist count];
}
-(id)initWithBasepath:(NSString *)basepath
TargetPathArr:(NSArray *)targetpaths{
    self.basepath = basepath;
    _targetPathArray = [[NSMutableArray alloc]initWithArray:targetpaths];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * Max= [userDefaults valueForKey:@"kMaxRequestCount"];
    if (Max==nil) {
        [userDefaults setObject:@"5" forKey:@"kMaxRequestCount"];
        Max =@"5";
    }
    [userDefaults synchronize];
    maxcount = [Max integerValue];
    _filelist = [[NSMutableArray alloc]init];
    _downinglist=[[NSMutableArray alloc] init];
    self.isFistLoadSound=YES;
    return  [self init];
}

- (id)init
{
	self = [super init];
	if (self != nil) {
        self.count = 0;
        if (self.basepath!=nil) {
            [self loadTempfiles];
            
        }

    }
	return self;
}
-(void)cleanLastInfo{
    for (ASIHTTPRequest *request in _downinglist) {
        if([request isExecuting])
            [request cancel];
    }
    [_downinglist removeAllObjects];
    [_filelist removeAllObjects];
}
+(FilesDownManage *) sharedFilesDownManageWithBasepath:(NSString *)basepath
                                         TargetPathArr:(NSArray *)targetpaths{
    @synchronized(self){
        if (sharedFilesDownManage == nil) {
            sharedFilesDownManage = [[self alloc] initWithBasepath: basepath  TargetPathArr:targetpaths];
        }
    }
    if (![sharedFilesDownManage.basepath isEqualToString:basepath]) {
        [sharedFilesDownManage cleanLastInfo];
        sharedFilesDownManage.basepath = basepath;
         [sharedFilesDownManage loadTempfiles];
    }
   sharedFilesDownManage.basepath = basepath;
   sharedFilesDownManage.targetPathArray =[NSMutableArray arrayWithArray:targetpaths];
    return  sharedFilesDownManage;
}
+(FilesDownManage *) sharedFilesDownManage{
    @synchronized(self){
        if (sharedFilesDownManage == nil) {
            sharedFilesDownManage = [[self alloc] init];
        }
    }
    return  sharedFilesDownManage;
}
+(id) allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (sharedFilesDownManage == nil) {
            sharedFilesDownManage = [super allocWithZone:zone];
            return  sharedFilesDownManage;
        }
    }
    return nil;
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error=[request error];
    if (error.code==4) {
        return;
    }
    if ([request isExecuting]) {
        [request cancel];
    }
    FileModel *fileInfo =  [request.userInfo objectForKey:@"File"];
    fileInfo.isDownloading = NO;
    fileInfo.willDownloading = NO;
    fileInfo.error = YES;
    for (FileModel *file in _filelist) {
        if ([file.fileName isEqualToString:fileInfo.fileName]) {
            file.isDownloading = NO;
            file.willDownloading = NO;
            file.error = YES;
        }
    }
    [self.downloadDelegate updateCellProgress:request];
}

-(void)requestStarted:(ASIHTTPRequest *)request
{
}

-(void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    FileModel *fileInfo=[request.userInfo objectForKey:@"File"];
    NSString *len = [responseHeaders objectForKey:@"Content-Length"];
    if ([fileInfo.fileSize longLongValue]> [len longLongValue]){return;}
        fileInfo.fileSize = [NSString stringWithFormat:@"%lld",  [len longLongValue]];
        [self saveDownloadFile:fileInfo];
}
-(void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes
{
    FileModel *fileInfo=[request.userInfo objectForKey:@"File"];
    NSLog(@"%@,%lld",fileInfo.fileReceivedSize,bytes);
    if (fileInfo.isFirstReceived) {
        fileInfo.isFirstReceived=NO;
        fileInfo.fileReceivedSize =[NSString stringWithFormat:@"%lld",bytes];
    }
    else if(!fileInfo.isFirstReceived)
    {
        fileInfo.fileReceivedSize=[NSString stringWithFormat:@"%lld",[fileInfo.fileReceivedSize longLongValue]+bytes];
    }
    if([self.downloadDelegate respondsToSelector:@selector(updateCellProgress:)])
    {
        [self.downloadDelegate updateCellProgress:request];
    }
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
    FileModel *fileInfo=(FileModel *)[request.userInfo objectForKey:@"File"];
    QuanJing *qj = [[QuanJing alloc]initWithDictionary:fileInfo.quanjing];
    NSString *packetPath = [CommonHelper getDirectoryPathWithExistCreat: [TEMPPATH stringByAppendingPathComponent: [NSString stringWithFormat:@"%@",qj.sid]]];
    if ([fileInfo.fileType isEqualToString:@"0"]&&[qj.packet length]>0) {
        fileInfo.fileType = @"1";
        NSString *path = @"SVQJ";
        path= [CommonHelper getTargetPathWithBasepath:_basepath subpath:path];
        path = [CommonHelper getDirectoryPathWithExistCreat:[NSString stringWithFormat:@"%@/%@",path,qj.sid]];
        path = [path stringByAppendingPathComponent:@"packet.zip"];
        fileInfo.targetPath = path;
        fileInfo.tempPath =[packetPath stringByAppendingPathComponent: @"packet"];
        [self startLoad];
    }
    else{
        NSString *configPath=[TEMPPATH stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.plist",fileInfo.fileID]];
        NSFileManager *fileManager=[NSFileManager defaultManager];
        NSError *error;
        if([fileManager fileExistsAtPath:configPath])
        {
            [fileManager removeItemAtPath:configPath error:&error];
            if(!error)
            {
                NSLog(@"%@",[error description]);
            }
        }
        if ([[NSFileManager defaultManager] fileExistsAtPath:packetPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:packetPath error:nil];
        }
        [_filelist removeObject:fileInfo];
        [self startLoad];
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(unzipFile:) object:request];
        [thread start];
    }
}
- (void)updataListWithUnzip:(ASIHTTPRequest *)request
{
    FileModel *fileInfo=(FileModel *)[request.userInfo objectForKey:@"File"];
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSMutableArray *_QJData = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJData"]];
    for (NSDictionary *qj in _QJData) {
        if([[qj objectForKey:@"sid"] isEqualToString:fileInfo.fileID])
        {
            [_QJData removeObject:qj];
            break;
        }
    }
    [_QJData insertObject:fileInfo.quanjing atIndex:0];
    [_Data setObject:_QJData forKey:@"QJData"];
    [_Data synchronize];
    if([self.downloadDelegate respondsToSelector:@selector(finishedDownload:)])
    {
        [self.downloadDelegate finishedDownload:request];
    }
}
- (void)updataList:(ASIHTTPRequest *)request
{
    if([self.downloadDelegate respondsToSelector:@selector(errForUnzip:)])
    {
        [self.downloadDelegate errForUnzip:request];
    }
}
- (void)unzipFile:(ASIHTTPRequest *)request
{
    FileModel *fileInfo=(FileModel *)[request.userInfo objectForKey:@"File"];
    fileInfo.isUnzip = YES;
    NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
    NSString* savePath = [NSString stringWithFormat: @"%@/SVQJ/%@", docPath, fileInfo.fileID];
    NSString* imagePath = [NSString stringWithFormat: @"%@/SVQJ/%@/qjicon.png", docPath, fileInfo.fileID];
    if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
    }
    BOOL result = [SSZipArchive unzipFileAtPath:fileInfo.targetPath toDestination:savePath];
    if (result == TRUE){
    if ([[NSFileManager defaultManager] fileExistsAtPath:fileInfo.targetPath]) {
        if ([[NSFileManager defaultManager] removeItemAtPath:fileInfo.targetPath error:nil]) {
        }
    }
    [UIImagePNGRepresentation([UIImage imageNamed:@"Load"]) writeToFile:imagePath atomically:YES];
    }[_downinglist removeObject:request];
    if (result) {
        [self performSelectorOnMainThread:@selector(updataListWithUnzip:) withObject:request waitUntilDone:YES];
    }else{
        [self performSelectorOnMainThread:@selector(updataList:) withObject:request waitUntilDone:YES];
    }
}
-(void)restartAllRquests{
    for (ASIHTTPRequest *request in _downinglist) {
        if([request isExecuting])
            [request cancel];
    }
    [self startLoad];
}

@end
